<template>
  <div class="app-container main-box">
    <el-card class="border-none header-card mb8" shadow="never">
      <el-page-header :content="$route.meta.title" @back="$router.back()"/>
    </el-card>
    <!-- 添加或修改学习资料对话框 -->
    <el-card class="border-none save-card" shadow="never">
      <el-form ref="materialsRef" :model="form" :rules="rules" label-width="80px">


        <el-row>
          <el-col :span="24">
            <el-form-item label="名称" prop="title">
              <el-input v-model="form.title" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="隐藏" prop="hidden">
              <el-switch
                  v-model="form.hidden"
                  inline-prompt
                  :active-value="0"
                  :inactive-value="1"
              />
            </el-form-item>

          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="资料分类" prop="cid">
              <el-input v-model="form.cid" placeholder="请输入资料分类" />
            </el-form-item>
          </el-col>
        </el-row>



        <el-row>
          <el-col :span="24">
            <el-form-item label="撰写人" prop="writerId">
              <el-input v-model="form.writerId" placeholder="请输入撰写人" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="文件地址">
              <file-upload v-model="form.file"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="学习时长" prop="duration">
              <el-input v-model="form.duration" placeholder="请输入学习时长" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-select v-model="form.remark" filterable multiple placeholder="请选择备注">
                <el-option
                    v-for="item in MaterialsWriterDictList"
                    :key="item.id"
                    :label="item.id+'.'+item.name"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="form.sort" placeholder="请输入排序" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="阅读须知">
              <editor v-model="form.content" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>
      <div class="footer-btns">
        <div class="footer-btns__content">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup name="MaterialsSave">
import { listMaterials, getMaterials, delMaterials, addMaterials, updateMaterials } from "@/api/manager/materials";






import { getTableData } from "@/api/system/dict/data";


const { proxy } = getCurrentInstance();
const { sys_hidden, sys_deleted } = proxy.useDict('sys_hidden', 'sys_deleted');

const materialsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const route = useRoute()
const router = useRouter()
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dialogFullScreen = ref(false);
const daterangeCreateTime = ref([]);
const daterangeUpdateTime = ref([]);

const MaterialsWriterDictList = ref([]);


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    createTime: null,
    writerId: null,
  },
  rules: {
    title: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    hidden: [
      { required: true, message: "隐藏不能为空", trigger: "blur" }
    ],
    sort: [
      { required: true, message: "排序不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询学习资料列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeCreateTime && '' != daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0];
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1];
  }
  if (null != daterangeUpdateTime && '' != daterangeUpdateTime) {
    queryParams.value.params["beginUpdateTime"] = daterangeUpdateTime.value[0];
    queryParams.value.params["endUpdateTime"] = daterangeUpdateTime.value[1];
  }
  listMaterials(queryParams.value).then(response => {
    materialsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  proxy.$tab.closeOpenPage();
  router.back();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deleted: 0,
    title: null,
    hidden: 0,
    cid: null,
    createTime: null,
    updateTime: null,
    writerId: null,
    file: null,
    duration: null,
    remark: null,
    sort: null,
    content: ""
  };
  proxy.resetForm("materialsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = [];
  daterangeUpdateTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加学习资料";
}

/** 修改按钮操作 */
function handleUpdate(id) {
  reset();
  getMaterials(id).then(response => {
    form.value = response.data;
    if(form.value.remark){
      form.value.remark = form.value.remark.split(",");
      form.value.remark = form.value.remark.map(Number);
    }else{
      form.value.remark = [];
    }


    open.value = true;
    title.value = "修改学习资料";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["materialsRef"].validate(valid => {
    if (valid) {
      form.value.remark = form.value.remark.join(",");
      if (form.value.id != null) {
        updateMaterials(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          cancel()
        });
      } else {
        addMaterials(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          cancel()
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除学习资料编号为"' + ids + '"的数据项？').then(function() {
    return delMaterials(ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manager/materials/export', {
    ...queryParams.value
  }, `materials_${new Date().getTime()}.xlsx`)
}

function getTableDataList(){
  getTableData({
    tableName: "cms_materials_writer",
    code: "id",
    name: "name",
  }).then(response =>{
    MaterialsWriterDictList.value = response.data;
  })
}


const id = route.query && route.query.id;
if (id) {
  handleUpdate(id);
}
getTableDataList();


</script>
